package com.bearingnavi.android.listeners;

import android.view.MotionEvent;

import com.bearingnavi.android.services.LocationService;
import com.bearingnavi.android.views.RotateView;

public class RotationGestureListener {
	private static final int INVALID_POINTER_ID = -1;
	private float fX, fY, sX, sY;
	private int ptrID1, ptrID2 , pxAccuracy = 4, angleAccuracy = 1; // degrees
	private float nAngle;

	public RotationGestureListener() {
		ptrID1 = INVALID_POINTER_ID;
		ptrID2 = INVALID_POINTER_ID;
	}

	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getActionMasked()) {
		case MotionEvent.ACTION_DOWN:
			sX = event.getX();
			sY = event.getY();
			ptrID1 = event.getPointerId(0);
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			fX = event.getX();
			fY = event.getY();
			//focalX = Mathematics.getMidpoint(fX, sX);
			//focalY = Mathematics.getMidpoint(fY, sY);
			ptrID2 = event.getPointerId(event.getActionIndex());
			nAngle = 1000;
			break;
		case MotionEvent.ACTION_MOVE:

			if (ptrID1 != INVALID_POINTER_ID && ptrID2 != INVALID_POINTER_ID) {
				float nfX, nfY, nsX, nsY;
				nfX = event.getX(event.findPointerIndex(ptrID1));
				nfY = event.getY(event.findPointerIndex(ptrID1));
				nsX = event.getX(event.findPointerIndex(ptrID2));
				nsY = event.getY(event.findPointerIndex(ptrID2));
				
				if (Math.abs(nfX-fX) < pxAccuracy && Math.abs(nfY-fY) < pxAccuracy &&
						Math.abs(nsX-sX) < pxAccuracy && Math.abs(nsY-sY) < pxAccuracy) {
					break;
				}
				
				if (nAngle == 1000){
					nAngle = (float) Math.toDegrees(Math.atan2(nfY-nsY, nfX-nsX));
				}
				
				float angle = (float) Math.toDegrees(Math.atan2(nfY-nsY, nfX-nsX));
				if (Math.abs(angle - nAngle) < angleAccuracy){
					break;
				}

				RotateView.getInstance().rotate(nAngle - angle);
				LocationService.setRotateTimeout();
//				Log.d("BLA", angle+"");
				fX = nfX;
				fY = nfY;
				sX = nsX;
				sY = nsY;
				nAngle = (float) Math.toDegrees(Math.atan2(nfY-nsY, nfX-nsX));
			}
			break;
		case MotionEvent.ACTION_UP:
			ptrID1 = INVALID_POINTER_ID;
			break;
		case MotionEvent.ACTION_POINTER_UP:
			ptrID2 = INVALID_POINTER_ID;
			break;
		}
		return false;
	}
	
}
